#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <unistd.h>


int create_fakefile(char ffile[]){
    FILE *fp = fopen(ffile, "w");
    printf("ready\n");
    fclose(fp);
}

int gen_row( uint16_t row_data[], uint16_t row_num ){
    int i, j;
    for(i=0; i<1250*16; i+=16){
        for(j=0; j<16; j++){
            row_data[i+j] = j+row_num;
        }
    }
}

int gen_bin(char filename_root[] ){

    uint16_t *row_data = (uint16_t*)malloc(sizeof(uint16_t)*1250*16);
    
    int file_cnt = 0;
    char fname[1024];
    char ffname[1024];
    sprintf(fname, "%s_%d.bin", filename_root, file_cnt);
    sprintf(ffname, "%s_%d.fake", filename_root, file_cnt);
    FILE *fp = fopen(fname, "wb");
    
    int row_cnt=0;
    uint16_t n_row, n_col;
    for(n_row=0; n_row<4700; n_row++){
        
        gen_row( row_data, n_row );
        
        fwrite(row_data, sizeof(uint16_t), 1250*16, fp);
        
        row_cnt++;
        if(row_cnt == 100 ){
            file_cnt++;
            fclose(fp);
            fp = NULL;
            
            create_fakefile(ffname);
            printf("saved: %s\n", fname);
            
            if(file_cnt >= 47) 
                break;
            
            sprintf(fname, "%s_%d.bin", filename_root, file_cnt);
            sprintf(ffname, "%s_%d.fake", filename_root, file_cnt);
            fp = fopen(fname, "wb");
            row_cnt = 0;
            
            usleep(50000);
        }
    }

    free(row_data);

    if( fp != NULL )
        fclose(fp);
}

int main( int argc, char *argv[] ){

    if( argc < 2 ){
        printf("usage: %s filename_root\n", argv[0]);
        exit(0);
    }

    gen_bin(argv[1] );
    
    return 0;
}
